package com.zwy.springinner;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class SHA256WithSalt {

    // 生成随机盐
    public static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16]; // 16字节的盐
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt); // 将盐编码为Base64字符串
    }

    // 计算带盐的SHA-256哈希
    public static String hashPasswordWithSalt(String password, String salt) throws NoSuchAlgorithmException {
        // 将密码和盐组合在一起
        String combinedPasswordAndSalt = password + salt;

        // 获取SHA-256消息摘要实例
        MessageDigest digest = MessageDigest.getInstance("SHA-256");

        // 更新消息摘要对象的内容
        digest.update(combinedPasswordAndSalt.getBytes());

        // 执行哈希计算，并返回字节数组
        byte[] hashBytes = digest.digest();

        // 将字节数组转换为Base64字符串
        return Base64.getEncoder().encodeToString(hashBytes);
    }

    // VEuegAZSsjmZd8Y4lDNR+w==
    // nXz5oe034mLFMzs8wQjyRJs0mjo8SYVHKsiJN6FO4d8=
    public static void main(String[] args) {
        try {
            // 用户输入的密码
            String password = "ibox@123456";

            // 生成随机盐
            String salt = generateSalt();
            System.out.println("Generated Salt: " + salt);

            // 计算带盐的哈希值
            String hashedPassword = hashPasswordWithSalt(password, salt);
            System.out.println("Hashed Password with Salt: " + hashedPassword);

            // 验证过程（假设你已经存储了盐和哈希后的密码）
            String storedSalt = salt; // 这里假设我们已经存储了盐
            String storedHashedPassword = hashedPassword; // 假设我们已经存储了哈希后的密码

            // 用户再次输入密码以验证
            String inputPassword = "ibox@123456";
            String inputHashedPassword = hashPasswordWithSalt(inputPassword, storedSalt);

            if (storedHashedPassword.equals(inputHashedPassword)) {
                System.out.println("Password verification successful!");
            } else {
                System.out.println("Password verification failed.");
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}
